<?php

namespace App\Http\Controllers\Client\Shop\Explore;

use App\Http\Controllers\ClientController;
use App\Models\Common\Common;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreConfirmController extends ClientController
{

    protected $work_id;
    protected $accept;
    protected $accept_remark;

    protected $work_msg;
    protected $shop;

    /**
     * 店主验收
     */
    public function index()
    {
        $all = $this->all;
        $this->work_id = $all['work_id'];
        $this->accept = $all['accept'];
        $this->accept_remark = $all['accept_remark'];


        try {
            DB::beginTransaction();
            // 检查当前工单状态，仅为已投稿状态可以验收(写锁)
            $this->work_msg = DB::table('explore_work')
                ->where('work_id', '=', $this->work_id)
                ->lockForUpdate()
                ->first();
            $this->work_msg = json_decode(json_encode($this->work_msg), true);
            if ($this->work_msg['status'] !== Data::DATA_DB_EXPLORE_WORK_STATUS_SUBMIT) {
                DB::rollBack();
                return $this->setReturnJson(-1, '当前工单状态不允许验收，请刷新重试');
            }

            // 查询店铺信息
            $shop = DB::table('shop')->where('shop_id','=',$this->work_msg['shop_id'])->first();
            $this->shop = json_decode(json_encode($shop), true);

            if ($this->accept) {
                // 验收
                self::confirm();
                DB::commit();
                return $this->setReturnJson(0, '验收成功');
            } else {
                // 拒回
                self::refuse();
                DB::commit();
                return $this->setReturnJson(0, '拒回成功');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(ExploreConfirmController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, $this->accept ? '验收失败' : '结算失败', ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }

    }

    /**
     * 验收通过
     */
    private function confirm()
    {
        // 修改状态
        DB::table('explore_work')
            ->where('work_id', '=', $this->work_id)
            ->update([
                'status' => Data::DATA_DB_EXPLORE_WORK_STATUS_ACCEPTED,
                'accept_time' => date('Y-m-d H:i:s'),
                'accept_remark' => $this->accept_remark,
            ]);
        // 记录日志
        DB::table('explore_work_log')->insert([
            'work_id' => $this->work_id,
            'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_ACCEPTED,
            'we_id' => $this->we_id,
            'remark' => '店主验收投稿，验收备注：' . $this->accept_remark,
        ]);

        // 验收超时自动进入待结算阶段
        // 生产环境7天超时，测试环境7分钟
        if (strtotime(date('Y-m-d H:i:s')) - strtotime($this->work_msg['submit_time']) > Period::getSetting('EXPLORE_CHECK_TIME')) {
            DB::table('explore_work')
                ->where('work_id', '=', $this->work_id)
                ->update(['status' => Data::DATA_DB_EXPLORE_WORK_STATUS_CHECK]);
            DB::table('explore_work_log')->insert([
                'work_id' => $this->work_id,
                'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_CHECK,
                'we_id' => $this->we_id,
                'remark' => '验收投稿超时，自动进入待结算阶段',
            ]);
        }
        // 发送验收微信通知（发送给达人）
        $data = [
            'first' => '您在店铺【'.$this->shop['shop_name'].'】的投稿已通过商家审核',
            'keyword1' => $this->work_msg['work_no'],
            'keyword2' => date('Y-m-d H:i:s'),
            'keyword3' => '验收已通过',
            'keyword4' => $this->accept_remark,
            'keyword5' => '店主',
        ];
        //发送通知
        $openid = DB::table('lottery_users')->where('we_id', '=', $this->work_msg['receiver_we_id'])->value('openid');
        Common::sendLaifeiMessage($openid, 'work_check', $data, '/talent/history?tab=1');

    }

    /**
     * 验收拒回
     */
    private function refuse()
    {
        $now = date('Y-m-d H:i:s');
        DB::table('explore_work')
            ->where('work_id', '=', $this->work_id)
            ->update([
                'status' => Data::DATA_DB_EXPLORE_WORK_STATUS_REFUSE,
                'accept_remark' => $this->accept_remark,
                'refused_at'=>$now,
                'hang_up'=>0,
            ]);
        DB::table('explore_work_log')->insert([
            'work_id' => $this->work_id,
            'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_REFUSE,
            'we_id' => $this->we_id,
            'remark' => '店主拒回投稿，验收备注：' . $this->accept_remark,
        ]);

        //  发送验收拒回微信通知（发送给达人）
        $data = [
            'first' => '您在店铺【'.$this->shop['shop_name'].'】提交的探店投稿未能达到店主的要求，现已驳回，请重新提交。',
            'keyword1' => '您的投稿已被驳回',
            'keyword2' => '店主',
            'keyword3' => $this->accept_remark,
            'keyword4' => $now,
            'remark' => [
                'value' => '请在48小时内重新提交投稿，订单超时将自动取消。',
                'color' => '#F00'
            ],
        ];
        //发送通知
        $openid = DB::table('lottery_users')->where('we_id', '=', $this->work_msg['receiver_we_id'])->value('openid');
        Common::sendLaifeiMessage($openid, 'work_reject', $data, '/talent/history?tab=1');

    }

}
